#ifndef _myPressure_H_
#define _myPressure_H_

#include <Arduino.h>
#include <Wire.h>

#define LTC2309_ADDRESS 0x18 // 多通道模拟传感器，LTC2309的I2C地址

uint16_t ReadLTC2309ADC(uint8_t cmdData)
{
  uint16_t adcValue = 0;
  Wire.beginTransmission(LTC2309_ADDRESS);       // 发送I2C起始信号
  Wire.write(cmdData << 2);                      // 将通道号移位并写入I2C总线
  Wire.endTransmission();                        // 发送I2C停止信号
  delayMicroseconds(100);                        // 等待ADC完成转换
  if (Wire.requestFrom(LTC2309_ADDRESS, 2) == 2) // 请求从LTC2309读取2个字节的数据
  {
    byte msb = Wire.read();             // 读取高位字节
    byte lsb = Wire.read();             // 读取低位字节
    adcValue = (msb << 4) | (lsb >> 4); // 将高位和低位字节组合成16位ADC值
  }
  return adcValue;
}

/// @brief 获取压力传感器对应的压力值
/// @param channel 传入当前传感器，总共5个传感器，Sensor0-Sensor3为一种，Sensor4为一种
/// @param pre 当前传感器的模拟量转换值
/// @return  当前的压力值，单位Kpa
uint16_t GetPressureValue(int channel, uint16_t *pre)
{
  uint16_t pressure = 0;
  switch (channel)
  {
  case 0:
    pressure = ReadLTC2309ADC(0x23); // 读取传感器0的ADC值,前面的数字来自硬件设计，Sensor0是CH0，单端
    break;
  case 1:
    pressure = ReadLTC2309ADC(0x07); // 读取传感器1的ADC值，Sensor1是CH1，单端
    break;
  case 2:
    pressure = ReadLTC2309ADC(0x0B); // 读取传感器2的ADC值，Sensor1是CH2+ CH3-，双极
    break;
  case 3:
    pressure = ReadLTC2309ADC(0x0F); // 读取传感器3的ADC值，Sensor1是CH4+ CH5-，双极
    break;
  case 4:
    pressure = ReadLTC2309ADC(0x33); // 读取传感器4的ADC值，Sensor1是CH6+ CH7-，双极
    break;
  default:
    break;
  }
  int16_t preKpa = 0; // 压力单位,Kpa
  if (pressure != 0)  // 若通信失败，模拟量值返回非零才能进行转换
  {
    if (channel == 4)
    {
      // preKpa = map(pressure, 320, 1674, 0, 400) / 1.0; // 将模拟量转换成压强
      preKpa = map(pressure, 320, 1350, 0, 300); // 将模拟量转换成压强
    }
    else
    {
      preKpa = map(pressure, 925, 4095, 0, 300); // 将模拟量转换成压强
    }
    if (pre) // 传入指针非空是将模拟量值赋给指针
    {
      *pre = pressure;
    }
  }
  return (preKpa < 0 ? 0 : preKpa);
}
/// @brief 获取压力传感器对应的压力值
/// @param channel 传入当前传感器，总共5个传感器，Sensor0-Sensor3为一种，Sensor4为一种
/// @return 当前的压力值，单位Kpa
uint16_t GetPressureValue(int channel)
{
  return GetPressureValue(channel, NULL);
}
/// @brief 显示模拟量值和压力值
void ShowPressureValue()
{
  Serial.println("Pressure start...");
  for (int i = 0; i <= 4; i++)
  {
    uint16_t pressureValue = 0;
    float pressureFloat = 0;
    pressureFloat = GetPressureValue(i, &pressureValue);
    // pressureFloat = GetPressureValue(i,NULL);
    Serial.print(pressureValue);
    Serial.print("->>");
    Serial.print(pressureFloat);
    Serial.println("Kpa");
  }
  Serial.println("Pressure end...");
}

#endif